﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace NetCoreDemo.MiddlWare
{

    /*中间件遵循 显式依赖原则 并在其构造函数中暴露所有依赖项。
     中间件能够利用到 UseMiddleware 扩展方法的优势，直接通过它们的构造函数注入服务，
     就像下面的例子所示。依赖注入服务是自动完成填充的，扩展所用到的 params 参数数组被用于非注入参数。*/
    public static class RequestCultureMiddlewareExtensions
    {
        public static IApplicationBuilder UseRequestCulture(this IApplicationBuilder builder)
        {
            return builder.UseMiddleware<RequestCultureMiddleware>();
        }
    }


    /*只要在其构造函数中获得下一个 RequestDelegate 并提供一个 Invoke方法，如下所示*/
    public class RequestCultureMiddleware
    {
        private readonly RequestDelegate _next;
        private readonly ILogger _logger;

        public RequestCultureMiddleware(RequestDelegate next, ILoggerFactory loggerFactory)
        {
            _logger = loggerFactory.CreateLogger<RequestCultureMiddleware>(); ;
            _next = next;
        }

        public async Task Invoke(HttpContext context)
        {
            _logger.LogInformation("地区请求处理开始: " + context.Request.Path);
            var status = context.Response.HasStarted;
            var cultureQuery = context.Request.Query["culture"];
            if (string.IsNullOrWhiteSpace(cultureQuery)) await _next.Invoke(context);
            else
            {
                var culture = new CultureInfo(cultureQuery);
                CultureInfo.CurrentCulture = culture;
                CultureInfo.CurrentUICulture = culture;
                await context.Response.WriteAsync(culture.DisplayName, Encoding.GetEncoding("GB2312"));
            }
            _logger.LogInformation("地区请求处理结束.");
        }
    }

    
}
